<template>
  <div class="create-box">
    <div class="item">
      <el-button
          text
          @click="show"
          bg
          style="font-family: dingding;font-size: 2vh"
      >
        发起流程
      </el-button>
    </div>
  </div>


  <div class="shade" v-if="isShadeShow" data-aos="fade-left"></div>

  <div class="form" data-aos="fade-left" v-if="isShadeShow">
    <div class="form-title">
      通用申请
    </div>
    <div class="leave-form">
      <el-form
          ref="ruleFormRef"
          style="max-width: 60vw"
          :model="seal_form"
          label-width="auto"
          class="demo-ruleForm"
          size="default"
          status-icon
      >
        <el-form-item label="标题" class="el-form-items">
          <el-input v-model="seal_form.title" style="width: 240px" placeholder="填写标题"/>
        </el-form-item>
        <el-form-item label="描述" class="el-form-items" id="form-content" style="height: 28vh">
          <el-input
            v-model="seal_form.content"
            placeholder="填写描述"
            :autosize="{ minRows: 10, maxRows: 15 }"
            type="textarea"
          />
        </el-form-item>
        <el-form-item label="审核人员" class="el-form-items">
          <el-cascader
              v-model="seal_form.operator"
              :options="operatorOptions"
              :show-all-levels="false"
              placeholder="请选择审核人"
              :props="props"
              clearable
              @change="checkLegal1"
          />
        </el-form-item>
        <el-form-item label="抄送人员" class="el-form-items">
          <el-cascader
              v-model="seal_form.copy"
              :options="copyOptions"
              :show-all-levels="false"
              placeholder="请选择抄送人"
              :props="props"
              clearable
              @change="checkLegal2"
          />
        </el-form-item>
        <el-form-item label="附件" class="el-form-items upload-items">
          <el-upload
              v-model:file-list="seal_form.file"
              class="upload-demo"
              :action="createURL"
              multiple
              :limit="1"
              :on-exceed="handleExceed"
              :on-change="handleSealFileChange"
              :on-success="handleSealFileSuccess"
              :auto-upload="false"
          >
            <!--style="    height: 90%;display: flex;flex-direction: column;"-->
            <el-button size="small">点击上传</el-button>
            <div class="el-upload__text" style="font-family: dingding">
              单次仅可上传一个文件
            </div>
          </el-upload>
        </el-form-item>
        <div class="btn-box" style="margin-top: 3vh;">
          <el-button type="primary" @click="submitForm()">
            提交
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
  <div class="close-btn" @click="closeForm" data-aos="fade-left" v-if="isShadeShow">
    <span>关</span>
    <span>闭</span>
  </div>

  <CreateFinance ref="createFinanceRef"/>
</template>

<script setup>
import {Briefcase, List, Stamp, WalletFilled,} from "@element-plus/icons-vue"
import {ElButton, ElDatePicker, ElForm, ElMessage, ElUpload} from "element-plus"
import {onMounted, reactive, ref, watch} from "vue"
import emitter from "@/lib/eventBus"
import {checkUserByRole, submitFlow, getLeaveFlowList} from "@/api"
import {createMsg, getTime, hasEmptyValue} from "@/lib/utils.js"
import CreateFinance from "@/components/Finance/Bill/CreateFinance.vue"
import {createSealApprove, getOperators, getStartOperator} from "@/api/OA/Seal"
import {createURL, resubmitURL} from "@/api/http"
import {createApp} from "@/api/OA/Approve"

//遮罩层
const isShadeShow = ref(false)

//审核人级联选择
const operatorOptions = ref([])
const props = { multiple: true }
//审核人级联选择
const copyOptions = ref([])

//请假表单
let seal_form = reactive({
  title : '',
  content:'',
  operator:[],
  copy:[],
  file:[],
  userId:'',
})

const seal_file = ref([])

// 章类型 0 公章 1 法人章 2 合同章
const sealOption = [
  {
    value: 0,
    label: '公章',
  },{
    value: 1,
    label: '法人章',
  },{
    value: 2,
    label: '合同章',
  },
]

// 是否外接 0否 1是
const takeOption = [
  {
    value: 0,
    label: '否',
  },{
    value: 1,
    label: '是',
  },
]

//表单校验规则
const ruleFormRef = ref()
const sealRules = reactive({
  typeRule:[
    { required: true, message: '不能为空', trigger: 'blur' },
  ],
  projectRule:[
    { required: true, message: '不能为空', trigger: 'blur' },
  ],
  subjectRule:[
    { required: true, message: '不能为空', trigger: 'blur' },
  ],
  takeRule:[
    { required: true, message: '不能为空', trigger: 'blur' },
  ],
  useNumberRule:[
    { required: true, message: '不能为空', trigger: 'blur' },
  ],
  operatorRule:[
    { required: true, message: '不能为空', trigger: 'blur' },
  ],
  copyRule:[
    { required: true, message: '不能为空', trigger: 'blur' },
  ],
})
//用户信息
let user_info
//遮罩层
const users = ref([])
//时间戳
let now

const createFinanceRef = ref()

// 监听请假页面的显隐
emitter.on('showLeave',(t) => {
  isShadeShow.value = t
})

onMounted(()=>{
  getUserInfo()
  AOS.init()
  now = getTime()
  getCopyUserList()
  getUserList()
})

//获取用户信息
const getUserInfo = () => {
  user_info = JSON.parse(localStorage.getItem('syhyDocManSys'))
}


//获取级联用户列表
const getUserList = async () => {
  try {
    let arr = []
    const {data:res} = await getOperators(user_info.id)
    if (res.code === 200){
      res.data.forEach(item=>{
        let child = []
        item.users.forEach(item2=>{
          child.push({
            label:item2.user_name,
            value:item2.user_id
          })
        })
        arr.push({
          value:item.roleId,
          label:item.roleName,
          children:child
        })
      })
    }
    operatorOptions.value = arr
  } catch (e) {
    console.log(e)
  }
}

const getCopyUserList = async () => {
  try {
    let rolename = [];
    let roleUser = [];
    const { data: res } = await checkUserByRole();

    const values = Object.values(res.data);
    values.forEach(value => {
      let datas = Object.values(value);
      datas.forEach(data => {
        if (typeof data === "string") {
          rolename.push(data);
        } else {
          roleUser.push(data);
        }
      });
    });
    for (let i = 0; i < roleUser.length; i++) {
      copyOptions.value.push({
        label: rolename[i],
        value: null,
        children: []
      });
      if (roleUser[i] && roleUser[i].length > 0) {
        for (let j = 0; j < roleUser[i].length; j++) {
          copyOptions.value[i].children.push({
            label: roleUser[i][j].user_name,
            value: roleUser[i][j].user_id,
          });
        }
      }
    }
  } catch (e) {
    console.log(e);
  }
};

//遮罩层显隐
const show = () => {
  isShadeShow.value = !isShadeShow.value
}

// 当超出限制时，执行的钩子函数
const handleExceed = () => {
  createMsg('单次只能上传一个文件','warning')
}

const handleSealFileChange = (file) => {
  console.log(file.raw,'file.raw')
  seal_file.value = []
  seal_file.value.push(file.raw)
}

//
const handleSealFileSuccess = (file) => {
  console.log(file,'s')
}


//关闭、重置表单
const closeForm = () => {
  resetForm()
  isShadeShow.value = false
}

/*请假表单*/
const submitForm = async () => {
  try {
    seal_form.userId = user_info.id
    const hasEmpty = hasEmptyValue(seal_form)
    if (!seal_form.title) return createMsg('标题不能为空','warning',false)
    if (!seal_form.content) return createMsg('内容不能为空','warning',false)
    if (!seal_form.operator.length) return createMsg('至少选择一个审核人','warning',false)
    if (!seal_file.value.length) return createMsg('附件不能为空','warning',false)
    let operator = []
    let copy = []
    seal_form.operator.forEach(item=>{
      operator.push(item[1])
    })
    if (seal_form.copy.length){
      seal_form.copy.forEach(item=>{
        copy.push(item[1])
      })
    }
    const form = new FormData();
    form.append("uploader", user_info.id);
    form.append("role", user_info.role);
    form.append("title", seal_form.title);
    form.append("content", seal_form.content);
    form.append("operator", operator.join(' '));
    form.append("copy", copy.length ? copy.join(' ') : null);
    form.append("file",seal_file.value[0])
    const {data:res} = await createApp(form)
    console.log(res)
    if (res.code === 200){
      closeForm()
      emitter.emit('reloadSeal')
      return createMsg('操作成功!','success',true)
    } else if (res.code === 405){
      return createMsg('上传文件无效，请检查文件有效性后重新上传','warning',true)
    } else  {
      closeForm()
      return createMsg('操作失败','info',true)
    }
  } catch (e) {
    console.log(e)
  }
}

function removeSingleQuotes(str) {
  return str.slice(1, -1);
}

const handleChange1 = () => {
}

const handleChange2 = () => {
}

const computeDate = (day1,day2) => {
  let start = new Date(day1);
  let end = new Date(day2);
  let workdayCount = 0;
  for (let date = start; date <= end; date.setDate(date.getDate() + 1)) {
    //Date 对象的 getDay() 方法可以获取日期对应的星期几，返回值范围是 0 到 6，分别代表周日到周六。
    if (date.getDay() >= 1 && date.getDay() <= 5) {
      workdayCount++;
    }
  }
  return workdayCount
}


const createFinance = () => {
  createFinanceRef.value.show()
}

const resetForm = () => {
  seal_form.title = ''
  seal_form.content = ''
  seal_form.operator = []
  seal_form.copy = []
  seal_form.file = []
  seal_form.userId = ''
  seal_file.value = []
}


const checkLegal1 = (val) => {
  val.forEach(item=>{
    if (item.length === 1) {
      seal_form.operator = []
      return createMsg('请选择员工节点','warning',false)
    }
  })
}

const checkLegal2 = (val) => {
  val.forEach(item=>{
    if (item.length === 1) {
      seal_form.copy = []
      return createMsg('请选择员工节点','warning',false)
    }
  })
}
</script>

<style scoped lang="less">
.create-box{
  height: 4vh;
  width: 5vw;
  //background-color: pink;
  position: absolute;
  z-index: 999;
  left: 90vw;
  top: 2vh;
  font-size: 2vh;
  line-height: 4vh;
  font-family: dingding;
}
.shade{
  position: absolute;
  height: 100%;
  width: 100%;
  z-index: 800;
  left: 3vw;
  background-color: rgba(0,0,0,.7);
}
.form{
  position: absolute;
  left: 26vw;
  z-index: 950;
  height: 100vh;
  width: 74vw;
  background-color: white;
  padding: 20px;
  box-sizing: border-box;
  background-color: rgba(250, 250, 250);
  .form-title{
    text-align: left;
    font-size: 2.2vh;
    font-weight: 600;
    letter-spacing: 1px;
    padding-left: 2vh;
    margin-top: 1vh;
  }
  .leave-form{
    margin-top: 1vh;
    .el-form{
      padding: 2vh;
      .upload-items{
        height: 15vh !important;
        :deep(.el-form-item__label-wrap){
          margin-left: 0 !important;
          line-height: 15vh !important;
          height: 15vh !important;
        }
        :deep(.el-form-item__content){
          //line-height: 15vh !important;
          height: 15vh !important;
        }
        :deep(.el-upload){
          display: flex;
          justify-content: center;
          align-items: baseline;
          cursor: pointer;
          outline: 0;
          flex-direction: column;
          padding-left: 3vw;
        }
        .upload-demo{
          :deep(.el-upload-list){
            margin-left: 2vw !important;
          }
        }
      }
      .el-form-items{
        border: 1px solid rgba(238, 238, 238);
        margin: 0 !important;
        //background-color: ;
        height: 8vh;
        align-items:center;
        justify-content: center;
        .el-form-item--default .el-form-item__label {
        }
        :deep(.el-form-item__label-wrap) {
          width: 10vw;
          line-height: 8vh;
          height: 8vh;
          text-align: center;
          box-sizing: border-box;
          border-right: 1px solid rgba(238, 238, 238);
          margin-left: 0 !important;
          &:last-child {
            border-right: none;
          }
        }
        :deep(.el-form-item__label){
          padding: 0 !important;
          margin: auto !important;
        }
        :deep(.el-range-editor.el-input__wrapper){
          width: 45vw;
          margin-left: 3vw;
        }
        :deep(.el-input) {
          width: 46vw !important;
          margin-left: 3vw;
        }
        :deep(.el-textarea ){
          width: 46vw !important;
          margin-left: 3vw;
        }

      }
    }
  }
}

.close-btn{
  position: absolute;
  top: 15vh;
  left: 24vw;
  height: 9vh;
  width: 3.5vw;
  z-index: 899;
  background-color: rgba(255, 87, 34);
  margin: 1vh auto;
  border: 2px solid white;
  box-sizing: border-box;
  border-radius: 5px;
  display: flex;
  justify-content: space-around;
  color: white;
  flex-direction: column;
  padding-left: 0.5vw;
  align-items: start;
  font-size: 1.6vh;
  &:hover{
    cursor: pointer;
  }
}

:deep(.el-form-item--default .el-form-item__content) {
  line-height: 32px;
  height: 8vh;
  background-color: #fff;
}
:deep(.el-cascader__tags){
  padding-left: 3vw !important;
}


#form-content{
  :deep(.el-form-item__label-wrap){
    height: 28vh;
  }
  :deep(.el-form-item__content){
    height: 28vh;
  }
  :deep(.el-textarea__inner){
    height: 21vh;
  }
}
</style>
